<template>
  <div class="w900">
    <el-button type="text" @click="showUploader = true" v-if=" ! showUploader">
      <span class="large">上传窗口</span> <i class="el-icon-arrow-down"></i>
    </el-button>
    <el-button type="text" v-if="excel && ! showUploader">
      <el-link type="success" :href="downloadTemplateUrl"><span class="fa fa-file-download success">&nbsp;下载Excel模板 </span></el-link>
    </el-button>

    <div class="uploadBox" v-if="showUploader">
        <el-form enctype="multipart/form-data">
            <div class="uploadBoxMain" v-if="!itemsAdded">
                <div class="form-group">
                    <div class="dropArea"
                      :style="`border: 2px dashed ${$store.state.effect.color};`"
                      @ondragover="onChange">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                          将文件拖到此处，或<em class="primary">点击上传</em>
                        </div>
                        <input type="file" id="items" name="items[]" required multiple @change="onChange">
                    </div>
                </div>
            </div>
            <div class="uploadBoxMain" v-else>
                <p>
                  <strong>名称</strong>
                </p>
                <span v-for="(name, index) in itemsNames"><strong> {{index + 1}}.</strong> {{name}}</span>
                <p>
                  <strong>大小</strong>
                </p>
                <span v-for="(size, index) in itemsSizes"><strong>{{index + 1}}.</strong> {{size}}</span>
                <p><strong>总文件数:</strong> {{itemsAdded}}</p>
                <p><strong>总上传大小:</strong> {{itemsTotalSize}}</p>
                <!-- Loader -->
                <div class="loader" v-if="isLoaderVisible">
                    <div class="loaderImg"></div>
                </div>
                <!-- End Loader -->
            </div>
            <div style="padding-top: 10px">
              <el-button type="primary"
              @click="onSubmit"
               v-if="itemsAdded >= minItems">
               上传<i class="el-icon-upload el-icon--right"></i>
             </el-button>
              <el-button @click="removeItems">
                收起 <i class="el-icon-arrow-up"></i>
              </el-button>
              <el-button type="text" v-if="excel && showUploader">
                <el-link type="success" :href="downloadTemplateUrl"><span class="fa fa-file-download success">&nbsp;下载Excel模板</span></el-link>
              </el-button>
            </div>
            <template v-if="errorMsg">
              <br>
              <div class="errorMsg">错误信息: {{errorMsg}}</div>
              <div class="errorMsg" v-if="itemsAdded && itemsAdded < minItems">Minimum {{minItems}} files need to be added to uploader. Please remove files and try again.</div>
            </template>
        </el-form>
    </div>

      <FileMeta :metas="fileMetas" :field="field"/>
  </div>
</template>

<script>
require('es6-promise').polyfill();
import axios from 'axios';
import * as constant from '@/store/yg/common/constant';
import FileMeta from './FileMeta'
import { transform, untransform } from '@/store/yg/common/uri'

export default {
  components: {
    FileMeta,
  },
  props: {
    postURL: {
        type: String,
        default: constant.API_SERVER + '/open/upload'
    },
    minItems: {
        type: Number,
        default: 1
    },
    method: {
        type: String,
        default: 'post'
    },
    postMeta: {
        type: [String, Array, Object],
        default: ''
    },
    fileMetas: {
      type: Array,
      default: e => []
    },
    field: {
      type: String,
    },
    entry: {
      type: Object,
    },
    excel: {
      type: Boolean,
      default: false,
    },
    downloadPath: {
      type: String,
      default: ''
    }
  },

  /*
   * The component's data.
   */
  data() {
    return {
      items: [],
      itemsAdded: '',
      itemsNames: [],
      itemsSizes: [],
      itemsTotalSize: '',
      formData: '',
      errorMsg: '',
      isLoaderVisible: false,
      showUploader: false,
    }
  },
  mounted() {
    this.showUploader = this.fileMetas.length == 0;
  },
  computed: {
    uri() {
      return untransform(this.entry.entryUri ? this.entry.entryUri: this.$route.params.uri);
    },
    isEdit() {
      return null != this.entry.entryUri;
    },
    downloadTemplateUrl() {
      if (this.downloadPath) {
        let p = this.downloadPath;
        if (p.indexOf("/") < 0) {
          p = "/" + p;
        } 
        return p;
      }
      return constant.API_SERVER + '/open/downloadTemplate?uri=' + untransform(this.$route.params.uri);
    }
  },
  methods: {
    // http://scratch99.com/web-development/javascript/convert-bytes-to-mb-kb/
    bytesToSize(bytes) {
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      if (bytes == 0) return 'n/a';
      let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
      if (i == 0) return bytes + ' ' + sizes[i];
      return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
    },

    onChange(e) {
      this.errorMsg = '';
      this.formData = new FormData();
      let files = e.target.files || e.dataTransfer.files;
      this.itemsAdded = files.length;
      let fileSizes = 0;
      for (let x in files) {
          if (!isNaN(x)) {
              this.items = e.target.files[x] || e.dataTransfer.files[x];
              this.itemsNames[x] = files[x].name;
              this.itemsSizes[x] = this.bytesToSize(files[x].size);
              fileSizes += files[x].size;
              this.formData.append('items[]', this.items);
          }
      }
      this.itemsTotalSize = this.bytesToSize(fileSizes);
    },

    removeItems() {
      this.showUploader = false;
      this.items = '';
      this.itemsAdded = '';
      this.itemsNames = [];
      this.itemsSizes = [];
      this.itemsTotalSize = '';
    },
    onSubmit() {
      this.isLoaderVisible = true;

      if (this.postMeta) {
        if ((typeof this.postMeta === 'string' && this.postMeta !== '') ||
            (typeof this.postMeta === 'object' && Object.keys(this.postMeta).length > 0)) {
            this.formData.append('postMeta', this.postMeta);
        }
      }
      let url = this.postURL + "?uri=" + this.uri + "&field=" + this.field + "&isEdit=" + this.isEdit;
      //console.log("client",this.$store.state.main.entry)
      if (this.$store.state.main.entry.client && this.$store.state.main.entry.client.class) {
        url += "&class=" + this.$store.state.main.entry.client.class;
      }
      if (this.method === 'put' || this.method === 'post' ) {
          axios({
            method: this.method,
            url: url,
            data: this.formData,
          })
          .then((response) => {
              this.isLoaderVisible = false;
              // Show success message
              if ( ! this.$store.state.edit.row[this.field]) {
                this.$store.state.edit.row[this.field] = [];
              }
              for (var i = 0; i < response.data.length; i++) {
                this.fileMetas.push(response.data[i]);
              }
              this.$store.state.edit.dataChanged = true;
              this.$store.state.edit.editWarningMessage = 'upload_file_well_info';
              this.$store.state.edit.blinkWarning = true;
              this.removeItems();
          })
          .catch((error) => {
              this.isLoaderVisible = false;
              console.log(error)
              this.errorMsg = error.response.data? error.response.data.error : '';
              this.removeItems();
              console.log(error)
          });
      } else {
          this.errorMsg = "This HTTP method is not allowed. Please use either 'put' or 'post' methods.";
          this.removeItems();
      }
    },
  }
}
</script>

<style>
.uploadBox {
    position: relative;
    padding: 0 1em 1em 1em;
}

.uploadBox h3 {
    padding-top: 1em;
}

.uploadBox .uploadBoxMain {
    position: relative;
}

/* Drag and drop */
.uploadBox .dropArea {
    position: relative;
    width: 100%;
    height: 300px;
    text-align: center;
    font-size: 2em;
    padding-top: 80px;
    background-color: #fff;
}

.uploadBox .dropArea input {
    position: absolute;
    cursor: pointer;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
}
/* End drag and drop */

/* Loader */
.uploadBox .loader {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    opacity: 0.9;
}

.uploadBox .loaderImg {
    border: 9px solid #eee;
    border-top: 9px solid #00ADCE;
    border-radius: 50%;
    width: 70px;
    height: 70px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
/* End Loader */

.uploadBox .errorMsg {
    font-size: 2em;
    color: #a94442;
}

.uploadBox .successMsg {
    font-size: 2em;
    color: #3c763d;
}

.uploader th {
  font-weight: bold;
  background-color: beige;
}

.uploader td, .uploader th {
    padding: 5px;
}
</style>
